<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/6/10 0010
 * Describe: 富友支付类加密类
 */

namespace app\api\controller\fuyou;

/**
 * PHP版3DES加解密类
 * 可与java的3DES(DESede)加密方式兼容
 */
class CryptDes {

    /**
     * 3des加密
     * @param string $str 待加密的字符串
     * @param string $key 加密用的密钥
     * @return string
     */
    public static function encrypt($str,$key){
        $str = self::pkcs5_pad($str, 8);
        if (strlen($str) % 8) {
            $str = str_pad($str,strlen($str) + 8 - strlen($str) % 8, "\0");
        }
        $sign = openssl_encrypt($str,'DES-EDE3' ,$key,OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);
        return strtoupper(bin2hex($sign));
    }

    /**
     * des加密，ecb
     * @param string $str
     * @param string $key
     * @return string
     */
    public static function encrypt_base64($str,$key){
        $str = self::pkcs5_pad($str, 8);
        if (strlen($str) % 8) {
            $str = str_pad($str,strlen($str) + 8 - strlen($str) % 8, "\0");
        }
        $sign = openssl_encrypt($str,'DES-ECB' ,$key,OPENSSL_RAW_DATA);
        return base64_encode($sign);
    }

    /**
     * des解密
     * @param string $str
     * @param string $key
     * @return string
     */
    public static function decrypt_base64($str,$key){
        $sign = openssl_decrypt(base64_decode($str),'DES-ECB' ,$key,OPENSSL_RAW_DATA);
        return $sign;
    }

    /**
     * 数据填充
     * @param string $text 填充数据
     * @param integer $blocksize 填充位数
     * @return string
     */
    private static function pkcs5_pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
}
?>